import Vue from 'vue'
import Router from 'vue-router'
import routes from './router'
import store from '../store'
Vue.use(Router)

let router =  new Router({
  routes,
  scrollBehavior(to, from, savedPosition) {
    return { x: 0, y: 0 }
  }
})

router.beforeEach((to, from, next) => {
  store.commit("cleftnav", to.fullPath);
  if (to.matched.some(record => record.meta.requiresAuth)){
    if(store.state.islogin){
      let level = store.state.admin.level;
      if(level==1){
        next();
      }else if(level==2){
        next();
        router.push('/')
      }else if(level==3){
        let url = "/admin,/account,/accountadd";
        if(url.indexOf(to.path)>=0&&to.path!='/'){
          next()
          router.push('/shophome');
        }else{
          next();
        }

        router.app.$http.get('/admin/islogin').then((res) => {
          if (res.data.data == 1) {
            store.commit('clogin',true);
            store.commit('cadmin',res.data.result);
          }else{
            store.commit('clogin',false);
            next();
            router.push('/')
          }
        })
        
      }else if(level==4){
        next();
        router.push('/')
      }
    }else{
      router.app.$http.get('/admin/islogin').then((res) => {
        if (res.data.data == 1) {
          store.commit('clogin',true);
          store.commit('cadmin',res.data.result);
          next()
          router.push('/admin');
        } else {
          next();
          router.push('/')
        }
      })
    }
  }else{
    next();
  }
  
})

export default router;